package model

import (
	"database/sql/driver"
	"encoding/json"
	"errors"
	"fmt"
	"time"

	"gorm.io/gorm"
)

type GormList []string

// Value 实现 driver.Valuer 接口，Value 返回 json value。序列化成json字符串存入数据库
func (g GormList) Value() (driver.Value, error) {
	if len(g) == 0 {
		return nil, nil
	}
	return json.Marshal(g)
}

// Scan 实现 sql.Scanner 接口，Scan 将 value 扫描至 Jsonb。把数据库中读取的字符串反序列化成Go的数据类型
func (g *GormList) Scan(value interface{}) error {
	bytes, ok := value.([]byte) // 断言是否是[]byte类型
	if !ok {
		return errors.New(fmt.Sprint("Failed to unmarshal JSONB value:", value))
	}
	return json.Unmarshal(bytes, &g)
}

type BaseModel struct {
	ID        int32          `gorm:"primarykey" json:"id"`
	CreatedAt time.Time      `gorm:"column:add_time" json:"-"`
	UpdatedAt time.Time      `gorm:"column:update_time" json:"-"`
	DeletedAt gorm.DeletedAt `json:"-"`
	IsDeleted bool           `json:"-"`
}
